import { createSSRApp } from "vue";
import App from "./App.vue";
import uviewPlus from "uview-plus";
// 导入 pinia 实例
import pinia from "./stores";
import "@/static/css/global.scss";

// 配置全局请求拦截，确保请求携带Cookie
const configureHttp = () => {
  // #ifdef H5
  // H5环境下特殊处理
  const oldRequest = uni.request;
  uni.request = (options = {}) => {
    options.withCredentials = true; // 确保发送Cookie
    return oldRequest(options);
  };
  // #endif

  // 全局请求拦截器
  uni.addInterceptor("request", {
    invoke(options) {
      // 添加跨域凭证支持
      options.withCredentials = true;

      // 支持OPTIONS预检请求
      if (!options.header) {
        options.header = {};
      }

      // 返回修改后的options
      return options;
    },
    success(res) {
      // 打印Cookie信息（仅开发调试用）
      if (res.cookies && res.cookies.length) {
        console.log("接收到的Cookies:", res.cookies);
      }
      return res;
    },
    fail(err) {
      console.error("请求失败:", err);
      return err;
    },
  });
};

export function createApp() {
  const app = createSSRApp(App);
  app.use(uviewPlus);
  app.use(pinia);
  // 配置HTTP拦截器
  configureHttp();

  return {
    app,
  };
}
